﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Globalization;
using EnvDTE;

namespace SPVisualDev.VSAddin.Dialogs.PropertySheets
{
    internal class CodeClassTypeConverter : TypeConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            string ret = string.Empty;
            if (value != null)
            {
                ret = ((CodeClass)value).FullName;
            }
            return ret;
        }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;
            else
                return false;
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
                return true;
            else
                return false;
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is CodeClass)
            {
                return value;
            }
            else
            {
                string className = value as string;
                if (string.IsNullOrEmpty(className))
                {
                    return null;
                }

                IPropertySheet sheet = context.Instance as IPropertySheet;
                CodeType t = sheet.ParentFeatureFolder.ContainingProject.CodeModel.CodeTypeFromFullName(className);
                if (t != null)
                {
                    return t as CodeClass;
                }
                else
                {
                    throw new Exception("Class '" + className + "' could not be found.");
                }
            }
        }
    }

}
